package com.atguigu.gmall.realtime.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

/**
 * @Author lzc
 * @Date 2023/2/21 08:56
 */
public class DimUtil {
    
    public static JSONObject readDimFromPhoenix(Connection conn, String table, Object id) throws Exception {
        // 1. 拼接一个 sql 语句
        String sql = "select * from " + table + " where id=?";
        
        Object[] args = new Object[]{id};
        
        // 2. 查询
        List<JSONObject> list = JdbcUtil.queryList(conn, sql, args, JSONObject.class, false);
        
        if (list.size() == 0) {
            throw new RuntimeException("你查询的表: " + table + " id=" + id + " 没有查询到对应的数据");
        }
        return list.get(0);
    }
    
    // TODO
    public static JSONObject readDim(Jedis redisClient, Connection conn, String table, Object id) throws Exception {
        
        // 1. 从 redis 读取维度数据
        JSONObject dim = readDimFromRedis(redisClient, table, id);
        // 2. 如果读到了维度: 则直接返回
        // 3. 如果没有读到维度: a: 取 phoenix 中读取 b:然后把读到的维度存入到 redis
        if (dim == null) {
            // 没有读到
            dim = readDimFromPhoenix(conn, table, id);
            // 把从 phoenix 读到的维度数据写入到 redis
            writeToRedis(redisClient, table, id, dim);
            System.out.println("走数据库: " + table + "  " + id);
        } else {
            System.out.println("走缓存: " + table + "  " + id);
        }
        return dim;
    }
    
    private static void writeToRedis(Jedis redisClient,
                                     String table,
                                     Object id,
                                     JSONObject dim) {
        // string:
        // key:  表名:id
        // value: json 格式字符串
        String key = getRedisKey(table, id);
        /*redisClient.set(key, dim.toJSONString());
        redisClient.expire(key, 2 * 24 * 60 * 60);*/
        redisClient.setex(key, 2 * 24 * 60 * 60, dim.toJSONString());
        
    }
    
    private static JSONObject readDimFromRedis(Jedis redisClient,
                                               String table,
                                               Object id) {
        String key = getRedisKey(table, id);
        String jsonStr = redisClient.get(key);
    
        JSONObject dim = null;
        if (jsonStr != null) {
            dim = JSON.parseObject(jsonStr);
        }
        return dim;
    }
    
    public static String getRedisKey(String table, Object id) {
        return table + ":" + id;
    }
    
    
}
